import { Table, TableProps } from "antd";
import dayjs from "dayjs";
import { Link } from "react-router-dom";
import { Pin } from "../../components/Pin";
import { useEditProject } from "../../hooks/useProjects";
import { More } from "./More";
import { Project } from "../../types/project";
import { User } from "../../types/user";
import { useProjectsQueryKey } from "./utils";

interface ListProps extends TableProps<Project> {
  users: User[];
}

export const List = ({ users, ...rest }: ListProps) => {
  const queryKey = useProjectsQueryKey();
  const { mutate: _pinProject } = useEditProject(queryKey);
  const pinProject = (id: number) => (pin: boolean) => _pinProject({ id, pin });

  return (
    <Table
      {...rest}
      rowKey="id"
      pagination={false}
      columns={[
        {
          title: <Pin checked={true} disabled={false} />,
          dataIndex: "pin",
          render(value, project) {
            return (
              <Pin checked={value} onCheckedChange={pinProject(project.id)} />
            );
          },
        },
        {
          title: "名称",
          dataIndex: "name",
          sorter: (a, b) => a.name.localeCompare(b.name),
          render(value, project) {
            return <Link to={String(project.id)}>{value}</Link>;
          },
        },
        {
          title: "部门",
          dataIndex: "organization",
        },
        {
          title: "负责人",
          render(value, project) {
            return (
              <span>
                {users.find((user) => user.id === project.personId)?.name ||
                  "未知"}
              </span>
            );
          },
        },
        {
          title: "创建时间",
          dataIndex: "created",
          render(value) {
            return (
              <span>{value ? dayjs(value).format("YYYY-MM-DD") : "无"}</span>
            );
          },
        },
        {
          render(value, project) {
            return <More project={project} />;
          },
        },
      ]}
    />
  );
};
